package com.yiwei.jmx.util;

import android.Manifest;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;

import com.afollestad.materialdialogs.MaterialDialog;
import com.yiwei.jmx.MainActivity;
import com.yiwei.jmx.R;
import com.yiwei.jmx.constant.Const;

import java.lang.ref.WeakReference;

/**
 * Created by xsooy-pc on 18-9-27.
 */

public class AppDownloadManager {
    private final WeakReference<Activity> weakReference;
    private DownloadBroadcastReceiver receiver;
    private DownloadChangeObserver downloadObserver;
    private DownloadManager manager;
    private MaterialDialog materialDialog;
    private long lastDownloadId = 0;
    private boolean isShowDialog = false;
    public static final Uri CONTENT_URI = Uri.parse("content://downloads/my_downloads");


    public AppDownloadManager(Activity activity) {
        weakReference = new WeakReference<Activity>(activity);

        //注册下载监听
        receiver = new DownloadBroadcastReceiver();
        weakReference.get().registerReceiver(receiver, new IntentFilter(
                DownloadManager.ACTION_DOWNLOAD_COMPLETE));

        showInstallDialog();
    }


    public class DownloadBroadcastReceiver extends BroadcastReceiver {

        public void onReceive(Context context, Intent intent) {


            try {
                if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {

                    long myDwonloadID = intent.getLongExtra(
                            DownloadManager.EXTRA_DOWNLOAD_ID, -1);

                    long refernece = PreferenceUtils.getLong(context, "downloadId", 0);

                    if (refernece == myDwonloadID) {
                        manager = (DownloadManager) context
                                .getSystemService(Context.DOWNLOAD_SERVICE);

//                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) installApp();
//                        else
                        DownloadUtil.installApp(weakReference.get(), myDwonloadID);

                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void showInstallDialog() {
        if (!isShowDialog) {
            isShowDialog = true;
            String updateContent = PreferenceUtils.getString(weakReference.get(), "upgrade_msg", "");
            if (updateContent.contains("{current_version}"))
                updateContent = updateContent.replace("{current_version}", Util.getVersion(weakReference.get()));
            if (updateContent.contains("{lastest_version}"))
                updateContent = updateContent.replace("{lastest_version}", PreferenceUtils.getString(weakReference.get(), "lastest_version", "1.0.0"));
            if (!Util.isWifi(weakReference.get()))
                updateContent = updateContent + ",\n当前网络不在WiFi环境，是否升级？";


//            String leftBtn;
//            if (PreferenceUtils.getInt(this, "forced_upgrade", 0) == 1)
//                leftBtn = "";
//            else leftBtn = "跳过";
            boolean isForce = true;
            if (PreferenceUtils.getInt(weakReference.get(), "forced_upgrade", 1) == 1)
                isForce = true;
            else isForce = false;
            Dialog.showVersionDialog(weakReference.get(), updateContent, isForce, new Dialog.DialogDefaultClickListener() {
                @Override
                public void confirm() {
                    isShowDialog = false;
                    if (!canDownloadState()) {
                        Dialog.showDefaultDialog(weakReference.get(), "提示", "请开启下载服务权限", weakReference.get().getResources().getString(R.string.cancel), "前往开启", true, new Dialog.DialogDefaultClickListener() {
                            @Override
                            public void confirm() {
                                String packageName = "com.android.providers.downloads";
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                intent.setData(Uri.parse("package:" + packageName));
                                weakReference.get().startActivity(intent);
                            }

                            @Override
                            public void cancel() {
                                showInstallDialog();
                            }
                        });
                        return;
                    }
                    downloadApp();
                }

                @Override
                public void cancel() {

                }
            });

        }
    }



    private boolean canDownloadState() {
        try {
            int state = weakReference.get().getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");

            if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
                return false;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private void downloadApp() {
        //判断是否6.0
        if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) && (ContextCompat.checkSelfPermission(weakReference.get(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {
            ActivityCompat.requestPermissions(weakReference.get(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    0);
        } else {
            initDownloadManager();
        }
    }


    /**
     * 初始化下载
     */
    public void initDownloadManager() {
        String url = PreferenceUtils.getString(weakReference.get(), "download_url", "");
        if (TextUtils.isEmpty(url)) return;

        if (materialDialog == null) {
            materialDialog = new MaterialDialog.Builder(weakReference.get())
                    .title("版本升级")
                    .content("正在下载安装包，请稍候..")
                    .progress(false, 100, true)
                    .cancelable(false)
                    .show();
        }

        try {
            manager = (DownloadManager) weakReference.get().getSystemService(Context.DOWNLOAD_SERVICE);
            Uri uri = Uri.parse(url);
            DownloadManager.Request request = new DownloadManager.Request(uri);

            // 设置下载路径和文件名
            request.setDestinationInExternalFilesDir(weakReference.get(), Environment.DIRECTORY_DOWNLOADS, Const.APP_NAME);
//            request.setDestinationInExternalPublicDir("download", Const.APP_NAME);

            request.setDescription(weakReference.get().getResources().getString(R.string.app_name)
                    + "正在下载安装包，请稍候..");

            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

            request.setMimeType("application/vnd.android.package-archive");

            // 设置为可被媒体扫描器找到
            request.allowScanningByMediaScanner();

            // 设置为可见和可管理
            request.setVisibleInDownloadsUi(true);

            lastDownloadId = manager.enqueue(request);

            // 把当前下载的ID保存起来
            PreferenceUtils.putLong(weakReference.get(), "downloadId", lastDownloadId);

            //采用内容观察者模式实现进度
            downloadObserver = new DownloadChangeObserver(null);
            weakReference.get().getContentResolver().registerContentObserver(CONTENT_URI, true, downloadObserver);

        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        }
    }



    private int p = 10;
    //用于显示下载进度
    private class DownloadChangeObserver extends ContentObserver {

        private DownloadChangeObserver(Handler handler) {
            super(handler);
        }

        @Override
        public void onChange(boolean selfChange) {
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(lastDownloadId);
            DownloadManager dManager = (DownloadManager) weakReference.get().getSystemService(Context.DOWNLOAD_SERVICE);
            final Cursor cursor = dManager.query(query);
            if (cursor != null && cursor.moveToFirst()) {
                final int totalColumn = cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
                final int currentColumn = cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
                int totalSize = cursor.getInt(totalColumn);
                int currentSize = cursor.getInt(currentColumn);
                float percent = (float) currentSize / (float) totalSize;
                int progress = Math.round(percent * 100);
                p = p + Util.getRandomNum(5, 15);
                if (progress < 80) {
                    if (p > 80) materialDialog.setProgress(80);
                    else
                        materialDialog.setProgress(p);
                } else
                    materialDialog.setProgress(progress);
                if (progress == 100) {
                    materialDialog.setProgress(100);
//                    materialDialog.dismiss();
                }
            }
        }


    }
}
